package cn.wei.youvierpc.server.tcp;

import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.parsetools.RecordParser;


public class TcpBufferHandlerWrapper implements Handler<Buffer> {

    private final RecordParser parser;

    public TcpBufferHandlerWrapper(Handler<Buffer> bufferHandler) {
        this.parser = initRecordParser(bufferHandler);
    }

    private RecordParser initRecordParser(Handler<Buffer> bufferHandler) {
        RecordParser recordParser = RecordParser.newFixed(8);
        recordParser.setOutput(new Handler<io.vertx.core.buffer.Buffer>() {
            int size = -1;
            io.vertx.core.buffer.Buffer resultBuffer = io.vertx.core.buffer.Buffer.buffer();
            @Override
            public void handle(io.vertx.core.buffer.Buffer buffer) {
                if (size == -1) {
                    size = resultBuffer.getInt(4);
                    recordParser.fixedSizeMode(size);

                    resultBuffer.appendBuffer(buffer);
                } else {
                    resultBuffer.appendBuffer(buffer);
                    System.out.println(resultBuffer.toString());

                    recordParser.fixedSizeMode(8);
                    size = -1;
                    resultBuffer = io.vertx.core.buffer.Buffer.buffer();
                }

            }
        });
        return recordParser;
    }

    @Override
    public void handle(Buffer buffer) {
        parser.handle(buffer);
    }
}
